package com.jiutong.meipengdai.utils;

import android.content.Context;
import android.os.Environment;

import com.jiutong.meipengdai.installapk.DownLoadService;
import com.jiutong.meipengdai.installapk.FileCallBack;
import com.jiutong.meipengdai.installapk.FileResponseBody;
import com.orhanobut.logger.Logger;
import com.tencent.tinker.lib.tinker.TinkerInstaller;
import com.tencent.tinker.loader.shareutil.SharePatchFileUtil;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Retrofit;
/**
 * Created by suxi on 2017/9/29.
 */

public class DownLoadUtil {
    private final Context mContext;
    private Retrofit.Builder retrofit;
    private String apkPatch;

    public DownLoadUtil(Context context){
        this.mContext = context;
    }
    /**
     * 目标文件存储的文件夹路径
     */
    private String destFileDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File
            .separator + "download";
    /**
     * 目标文件存储的文件名
     */
    private String destFileName = "patch.apk";

    /**
     * 初始化OkHttpClient
     *
     * @return
     */
    private OkHttpClient initOkHttpClient() {

        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.connectTimeout(100000, TimeUnit.SECONDS);
        builder.networkInterceptors().add(new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse
                        .newBuilder()
                        .body(new FileResponseBody(originalResponse))//将自定义的ResposeBody设置给它
                        .build();
            }
        });
        return builder.build();
    }

    /**
     * 下载文件
     */
    public void downloadPatch(String apk_Url) {
        if (retrofit == null) {
            retrofit = new Retrofit.Builder();
        }

        this.apkPatch = apk_Url;
        int indexOf = apk_Url.lastIndexOf("/");
        String apkUrl = apk_Url.substring(0, indexOf + 1);
        String apkName = apk_Url.substring(indexOf + 1, apk_Url.length());

        // 使用Retrofit进行文件的下载
        retrofit.baseUrl(apkUrl)
                .client(initOkHttpClient())
                .build()
                .create(DownLoadService.IFileLoad.class)
                .loadFile(apkName)
                .enqueue(new FileCallBack(destFileDir, destFileName) {

                    @Override
                    public void onSuccess(File file) {
                        Logger.e("sx", "请求成功");
                        loadPatch(file);
                    }

                    @Override
                    public void onLoading(long progress, long total) {
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Logger.e("sx", "请求失败" + t.toString());
                    }
                });
    }

    /**
     * 加载热补丁插件
     *
     * @param
     */
    public boolean loadPatch(File file) {

        if (!SharePatchFileUtil.isLegalFile(file)) {
            Logger.e("非法路径");
            return false;
        }

        String versionName = ExampleUtil.getVersion(mContext);
        SpConfig.getInstance().putString(versionName, apkPatch);
        Logger.d("filePatch == " + file.getPath()+", path == " + file.getAbsolutePath());
        TinkerInstaller.onReceiveUpgradePatch(mContext, file.getPath());
        return true;
    }

}
